<template>
	<view class="container">
	<view class="header">
		<text class="title">编辑盘点单</text>
		<view class="save-btn" @click="saveInventory">
			<text class="save-text">保存</text>
		</view>
	</view>

		<view class="content" v-if="form">
			<!-- 基本信息 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				<view class="form-grid">
					<view class="field">
						<text class="label">盘点单号</text>
						<input class="input" v-model="form.sessionNo" placeholder="盘点单号" disabled />
					</view>
					<view class="field">
						<text class="label">计划盘点日期</text>
						<picker mode="datetime" @change="onDateChange">
							<view class="input picker">{{ form.plannedDate || '请选择计划日期' }}</view>
						</picker>
					</view>
					<view class="field">
						<text class="label">备件仓库</text>
						<picker mode="selector" :range="warehouseList" range-key="name" @change="onWarehouseChange">
							<view class="input picker">{{ warehouseName || '请选择仓库' }}</view>
						</picker>
					</view>
					<view class="field">
						<text class="label">盘点人员</text>
						<input class="input" v-model="form.inventoryUser" placeholder="请输入盘点人员姓名" />
					</view>
					<view class="field">
						<text class="label">盘点状态</text>
						<picker mode="selector" :range="statusList" range-key="name" @change="onStatusChange">
							<view class="input picker">{{ statusName || '请选择状态' }}</view>
						</picker>
					</view>
				</view>
			</view>

			<!-- 备注信息 -->
			<view class="section">
				<view class="section-title">备注信息</view>
				<view class="remark-field">
					<textarea class="textarea" v-model="form.remark" placeholder="请输入备注信息（可选）" maxlength="200"></textarea>
					<text class="char-count">{{ form.remark.length }}/200</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
	</view>
</template>

<script>
import { getInventory, updateInventory } from '@/api/inventory/inventory.js'
import { listWarehouseDTO } from '@/api/inventory/warehouse.js'

export default {
	data() {
		return {
			sessionNo: '',
			loading: true,
			form: {
				sessionNo: '',
				plannedDate: '',
				warehouseCode: '',
				inventoryUser: '',
				status: '',
				remark: ''
			},
			warehouseList: [],
			warehouseName: '',
			statusList: [
				{ code: 'PENDING', name: '待盘点' },
				{ code: 'IN_PROGRESS', name: '盘点中' },
				{ code: 'COMPLETED', name: '盘点完成' },
				{ code: 'CANCELLED', name: '已取消' }
			],
			statusName: '',
			// 仓库映射
			warehouseMapping: {
				'WH001': '主仓库',
				'WH002': '备用仓库',
				'WH003': '临时仓库',
				'MAIN': '主仓库',
				'BACKUP': '备用仓库',
				'TEMP': '临时仓库'
			}
		}
	},
	onLoad(options) {
		if (options.sessionNo) {
			this.sessionNo = options.sessionNo
			this.loadData()
		} else {
			uni.showToast({ title: '缺少盘点单号', icon: 'none' })
			setTimeout(() => uni.navigateBack(), 1500)
		}
	},
	methods: {
		async loadData() {
			try {
				this.loading = true
				await Promise.all([
					this.loadInventoryDetail(),
					this.loadMeta()
				])
			} catch (e) {
				console.error('加载数据失败:', e)
				uni.showToast({ title: '加载失败', icon: 'none' })
			} finally {
				this.loading = false
			}
		},

		async loadInventoryDetail() {
			try {
				const res = await getInventory(this.sessionNo)
				console.log('盘点详情API返回:', res)
				
				if (res && res.code === 200 && res.data) {
					const data = res.data
					
					this.form = {
						sessionNo: data.sessionNo,
						plannedDate: this.formatDateForPicker(data.plannedDate),
						warehouseCode: data.warehouseCode,
						inventoryUser: data.inventoryUser || '',
						status: data.status || 'PENDING',
						remark: data.remark || ''
					}
					
					// 设置显示名称
					this.warehouseName = this.warehouseMapping[data.warehouseCode] || data.warehouseCode
					this.statusName = this.statusList.find(s => s.code === data.status)?.name || '待盘点'
					
					console.log('加载的盘点数据:', this.form)
				} else {
					uni.showToast({ title: res.msg || '获取盘点详情失败', icon: 'none' })
				}
			} catch (e) {
				console.error('加载盘点详情失败:', e)
				uni.showToast({ title: '加载失败', icon: 'none' })
			}
		},

		async loadMeta() {
			// 加载仓库列表
			try {
				const r = await listWarehouseDTO({})
				console.log('仓库API返回:', r)

				if (r && r.code === 200 && r.data && Array.isArray(r.data)) {
					this.warehouseList = r.data.map(w => ({
						code: w.code || w.id || w.warehouseCode || '',
						name: w.name || w.warehouseName || w.label || w.text
					}))
					console.log('仓库列表处理完成:', this.warehouseList)
				} else {
					console.log('仓库数据为空或格式不正确')
					this.warehouseList = []
				}
			} catch (e) {
				console.error('加载仓库列表失败:', e)
				this.warehouseList = []
			}
		},

		onDateChange(e) {
			const timestamp = e.detail.value
			const date = new Date(timestamp)
			this.form.plannedDate = date.toLocaleString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit'
			})
		},

		onWarehouseChange(e) {
			const index = e.detail.value
			const selected = this.warehouseList[index]
			this.form.warehouseCode = selected.code
			this.warehouseName = selected.name
		},

		onStatusChange(e) {
			const index = e.detail.value
			const selected = this.statusList[index]
			this.form.status = selected.code
			this.statusName = selected.name
		},

		// 格式化日期为picker格式
		formatDateForPicker(dateStr) {
			if (!dateStr) return ''
			const date = new Date(dateStr)
			return date.toLocaleString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit'
			})
		},

		async saveInventory() {
			try {
				// 验证必填字段
				if (!this.form.plannedDate) {
					uni.showToast({ title: '请选择计划盘点日期', icon: 'none' })
					return
				}
				if (!this.form.warehouseCode) {
					uni.showToast({ title: '请选择备件仓库', icon: 'none' })
					return
				}
				if (!this.form.inventoryUser) {
					uni.showToast({ title: '请输入盘点人员姓名', icon: 'none' })
					return
				}
				
				const payload = {
					sessionNo: this.form.sessionNo,
					plannedDate: this.form.plannedDate,
					warehouseCode: this.form.warehouseCode,
					inventoryUser: this.form.inventoryUser,
					status: this.form.status,
					remark: this.form.remark || ''
				}
				
				console.log('更新数据:', payload)
				
				uni.showLoading({ title: '保存中...' })
				const r = await updateInventory(payload)
				uni.hideLoading()
				
				if (r && r.code === 200) {
					uni.showToast({ title: '保存成功', icon: 'success' })
					setTimeout(() => uni.navigateBack(), 1500)
				} else {
					uni.showToast({ title: r.msg || '保存失败', icon: 'none' })
				}
			} catch (e) {
				uni.hideLoading()
				console.error('保存失败:', e)
				uni.showToast({ title: '保存失败: ' + (e.message || '未知错误'), icon: 'none' })
			}
		},

		goBack() {
			uni.navigateBack()
		}
	}
}
</script>

<style scoped>
.container {
	min-height: 100vh;
	background-color: #f5f6f7;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
}

.save-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.save-text {
	font-size: 28rpx;
	color: #4a94ff;
	font-weight: 500;
}

.content {
	padding: 20rpx;
}

.section {
	background: #fff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.section-title {
	font-size: 28rpx;
	font-weight: 600;
	color: #333;
	padding: 30rpx 30rpx 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-grid {
	padding: 20rpx 30rpx 30rpx;
}

.field {
	margin-bottom: 30rpx;
}

.field:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
	margin-bottom: 15rpx;
}

.input {
	width: 100%;
	height: 80rpx;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
}

.input.picker {
	display: flex;
	align-items: center;
	color: #666;
}

.input:disabled {
	background: #f5f5f5;
	color: #999;
}

.remark-field {
	padding: 20rpx 30rpx 30rpx;
	position: relative;
}

.textarea {
	width: 100%;
	min-height: 200rpx;
	background: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 12rpx;
	padding: 20rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
	resize: none;
}

.char-count {
	position: absolute;
	bottom: 40rpx;
	right: 40rpx;
	font-size: 24rpx;
	color: #999;
}

.loading {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}
</style>
